package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Customer;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.CustomerMapper;
import cn.wolfcode.crm.mapper.CustomerTraceHistoryMapper;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.qo.CustomerQueryObject;
import cn.wolfcode.crm.service.ICustomerService;
import cn.wolfcode.crm.util.EmployeeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CustomerServiceImpl implements ICustomerService {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private CustomerTraceHistoryMapper customerTraceHistoryMapper;


    @Override
    public void save(Customer customer) {
        Employee employee = EmployeeUtil.getEmployee();
        customer.setSeller(employee);
        customer.setInputUser(employee);
        customer.setInputTime(new Date());
        customerMapper.insert(customer);

    }

    @Override
    public void delete(Long id) {
        customerMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Customer customer) {
        customerMapper.updateByPrimaryKey(customer);
    }

    @Override
    public Customer get(Long id) {
        return customerMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Customer> listAll() {
        return customerMapper.selectAll();
    }

    @Override
    public PageInfo<Customer> query(CustomerQueryObject qo) {
        Employee employee = EmployeeUtil.getEmployee();
        List<Role> roles = roleMapper.selectSnByEmployee(employee.getId());
        for (Role role : roles) {

            if (!employee.isAdmin() && !role.getSn().equals("Market_Manager")) {
                qo.setSellerEId(employee.getId());
            }
        }

        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), "c.input_time DESC"); //对下一句sql进行自动分页
        List<Customer> customers = customerMapper.selectForList(qo); //里面不需要自己写limit
        for (Customer customer : customers) {
            int count = customerTraceHistoryMapper.selectCount(customer.getId());
            customer.setNum(count);
        }
        return new PageInfo<>(customers);
    }

    @Override
    public void updateStatus(Integer status, Long id) {
        customerMapper.updateStatus(status, id);
    }

}
